package com.shujia.jichu

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

object Demo20JDBC {
  def main(args: Array[String]): Unit = {
    /**
     *  scala中连接数据库
     */
    //加载驱动
    Class.forName("com.mysql.jdbc.Driver")

    //创建与数据库连接对象
    val conn: Connection = DriverManager.getConnection("jdbc:mysql://192.168.220.100/studentdb?useUnicode=true&characterEncoding=utf8&useSSL=false", "root", "123456")

    //为了防止sql注入
    val state: PreparedStatement = conn.prepareStatement("select id,name,age,gender,clazz from student where clazz=?")

    state.setString(1,"文科一班")

    //执行sql语句
    val resultSet: ResultSet = state.executeQuery()

    while (resultSet.next()){
      val id: Int = resultSet.getInt("id")
      val name: String = resultSet.getString("name")
      val age: Int = resultSet.getInt("age")
      val gender: String = resultSet.getString("gender")
      val clazz: String = resultSet.getString("clazz")
      println(s"学号:${id},姓名:${name},年龄:${age},性别:${gender},班级:${clazz}")
    }

    //释放资源
    state.close()
    conn.close()
  }

}
